<?php
namespace app\controller;

use app\BaseController;
use EasyWeChat\Factory;
use think\facade\Config;

class Wechat extends BaseController
{

    public function getConfig(): array
    {
        $wechat = Config::get('wechat');
        return [
            'app_id'     => $wechat['app_id'],
            'secret'     => $wechat['secret'],
            'mch_id'     => $wechat['pay']['mch_id'],
            'key'        => $wechat['pay']['v2_key'],
            'cert_path'  => $wechat['pay']['cert_path'],
            'key_path'   => $wechat['pay']['key_path'],
            'notify_url' => $wechat['pay']['notify_url'],
        ];
    }

    /**
     * 生产不重复的随机字符串
     */
    public function createNonceStr($length = 32)
    {
        $chars = "abcdefghijklmnopqrstuvwxyz0123456789";
        $str   = "";
        for ($i = 0; $i < $length; $i++) {
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return date('Ymd') . $str;
    }

    /**
     * 获取用户openid
     *
     */
    public function getOpenid()
    {
        $code = $this->request->param('code');
        if ($code) {
            // 创建微信小程序对象
            $wechat = Factory::miniProgram($this->getConfig());
            // 获取 session_key 和 openid
            $result = $wechat->auth->session($code);
            // 处理结果
            if (isset($result['openid'])) {
                // 业务处理
                return json(['code' => 1, 'data' => $result['openid'], 'msg' => '获取openid成功']);
            } else {
                // 报错 $res['errmsg']
                return json(['code' => 0, 'data' => '', 'msg' => $result['errmsg']]);
            }
        } else {
            return json(['code' => 0, 'data' => '', 'msg' => 'code不能为空']);
        }
    }

    /**
     * 获取用户手机号
     *
     */
    public function getPhoneNumber()
    {
        $phone_code = $this->request->param('phone_code');
        if ($phone_code) {
            $wechat = Factory::miniProgram($this->getConfig());
            $result = $wechat->phone_number->getUserPhoneNumber($phone_code);
            if (isset($result['phone_info'])) {
                // 业务处理
                return json(['code' => 1, 'data' => $result['phone_info']['phoneNumber'], 'msg' => '获取手机号成功']);
            } else {
                // 报错 $res['errmsg']
                return json(['code' => 0, 'data' => '', 'msg' => $result['errmsg']]);
            }
        } else {
            return json(['code' => 0, 'data' => '', 'msg' => 'phone_code不能为空']);
        }
    }

    /**
     * 微信支付
     */
    public function pay()
    {
        $open_id = $this->request->param('open_id');
        if ($open_id) {
            // 创建微信支付对象
            $wechat = Factory::payment($this->getConfig());
            // 组装请求参数
            $params = [
                'body'             => '1分钱支付测试',                                // 商品描述
                 'out_trade_no'     => $this->createNonceStr(10),                            // 商户订单号
                 'total_fee'        => 1,                                                    // 订单总金额，单位为分，只能为整数
                 'spbill_create_ip' => '',                                                   // 可选，如不传该参数，SDK 将会自动获取相应 IP 地址
                 'notify_url'       => 'https://你的线上地址/index.php/wechat/notify', // 支付结果通知网址，如果不设置则会使用配置里的默认地址
                 'trade_type'       => 'JSAPI',                                              // 请对应换成你的支付方式对应的值类型
                 'openid'           => $open_id,
            ];
            // 发起支付请求
            $result = $wechat->order->unify($params);
            // 处理支付结果
            if ($result['return_code'] === 'SUCCESS' && $result['result_code'] === 'SUCCESS') {
                                                                                       // 根据$result中的prepay_id生成签名等信息
                                                                                       // 将生成的信息返回给前端进行支付
                $response = $wechat->jssdk->bridgeConfig($result['prepay_id'], false); // 返回数组
                return json(['code' => 1, 'data' => $response, 'msg' => '微信支付成功']);
            } else {
                // 支付失败，处理错误信息
                return json(['code' => 0, 'data' => $result, 'msg' => '微信支付失败']);
            }
        } else {
            return json(['code' => 0, 'data' => '', 'msg' => 'open_id不能为空']);
        }
    }

    public function notify()
    {
        // 接收微信支付回调通知
    }

}
